# -*- coding: utf-8 -*-
# @Organization  : asiainfo
# @Author        : 周伟东
# @Time          : 2021/1/7 16:25
# @Function      : 模型模块
from datetime import datetime

from sqlalchemy import Column, BIGINT, INTEGER, String, CHAR, SMALLINT, DATETIME, BIGINT, TIMESTAMP, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

from app.constants import JOB_STATUS_READY, JOB_TYPE_ASSET, JOB_NOT_DELETED

Base = declarative_base()


class CyberspaceJob(Base):
    """
     cyberspace_job : 空间探测任务表
    """
    # 表名
    __tablename__ = 'CYBERSPACE_JOB'
    id = Column(BIGINT, primary_key=True, autoincrement=True, comment="id")
    job_name = Column(String(200), nullable=False, comment="任务名称")
    job_id = Column(CHAR(32), nullable=False, comment="任务id")
    job_creator = Column(String(100), nullable=False, default="anonymous", comment="任务创建者")
    job_type = Column(SMALLINT, nullable=False, default=JOB_TYPE_ASSET, comment="任务类型(1:资产扫描)")
    job_params = Column(String(1000), nullable=False, comment="任务参数")
    job_result = Column(String(1000), comment="任务统计信息")
    job_create_time = Column(DATETIME, default=datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'), comment="任务创建时间")
    job_start_time = Column(DATETIME, comment="任务开始时间")
    job_end_time = Column(DATETIME, comment="任务结束时间")
    job_consume_time = Column(BIGINT, default=-1, comment="任务消耗时间")
    job_complete_percent = Column(SMALLINT, default=0, comment="任务完成度")
    job_status = Column(SMALLINT, nullable=False, default=JOB_STATUS_READY, comment="任务状态(0:排队 1:开始 2:结束 3:失败)")
    org_id = Column(BIGINT, comment="所属机构id")
    tenant_id = Column(BIGINT)
    is_deleted = Column(SMALLINT, nullable=False, default=JOB_NOT_DELETED, comment="任务删除状态，0 未删除 1删除")

    @staticmethod
    def get_time():
        return datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')

    def set_job_start_time(self):
        self.job_start_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')

    def set_job_end_time(self):
        self.job_end_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')

    def set_job_consume_time(self):
        job_start_time_date = self.job_start_time
        job_end_time_date = self.job_end_time
        if job_start_time_date and job_end_time_date:
            if isinstance(job_end_time_date, str):
                job_end_time_date = datetime.strptime(job_end_time_date, "%Y-%m-%d %H:%M:%S")
            if isinstance(job_start_time_date, str):
                job_start_time_date = datetime.strptime(job_start_time_date, "%Y-%m-%d %H:%M:%S")
            self.job_consume_time = (job_end_time_date - job_start_time_date).seconds

    def set_job_status(self, job_status):
        self.job_status = job_status


class CyberspaceAssetResult(Base):
    """
     cyberspace_result : 空间探测结果表
    """
    # 表名
    __tablename__ = 'CYBERSPACE_ASSET_RESULT'
    id = Column(BIGINT, primary_key=True, autoincrement=True, comment="id")
    ip = Column(String(100), nullable=False, comment="ip地址")
    state = Column(SMALLINT, default=0, comment="主机状态 0 不在线 1 在线")
    hostname = Column(String(200), comment="主机名")
    mac = Column(String(200), comment="mac地址")
    mac_vender = Column(String(200), comment="主机提供商")
    os_version = Column(String(200), comment="操作系统版本")
    device_type = Column(String(200), comment="设备类型")
    port_nums = Column(INTEGER, comment="主机开发端口数量")
    os_info = Column(String(1000), comment="操作系统信息")
    job_id = Column(CHAR(32), nullable=False, comment="关联的任务id")
    job_name = Column(String(200), nullable=False, comment="任务名称")
    create_time = Column(DATETIME, default=datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'), comment="结果创建时间")
    org_id = Column(BIGINT, comment="所属机构id")
    tenant_id = Column(BIGINT)
    server_info = []


class CyberspaceAssetService(Base):
    """
     cyberspace_history_result : 空间探测结果历史表
    """
    # 表名
    __tablename__ = 'CYBERSPACE_ASSET_SERVICE'
    id = Column(BIGINT, primary_key=True, autoincrement=True, comment="id")
    job_id = Column(CHAR(32), nullable=False, comment="关联的任务id")
    ip = Column(String(100), nullable=False, comment="ip地址")
    asset_result_id = Column(BIGINT, ForeignKey('CYBERSPACE_ASSET_RESULT.id'), nullable=False, comment="资产结果id")
    port = Column(SMALLINT, nullable=False, comment="端口")
    state = Column(String(100), comment="服务状态 1 open 0 closed")
    protocol = Column(String(200), comment="服务协议")
    service = Column(String(200), comment="服务名称")
    version = Column(String(200), comment="服务版本")
    org_id = Column(BIGINT, comment="所属机构id")
    tenant_id = Column(BIGINT)
    to_result = relationship("CyberspaceAssetResult", backref="service2result")


class CyberspaceHistoryResult(Base):
    """
     cyberspace_history_result : 空间探测结果历史表
    """
    # 表名
    __tablename__ = 'CYBERSPACE_HISTORY_RESULT'
    id = Column(BIGINT, primary_key=True, autoincrement=True, comment="id")
    ip = Column(String(100), nullable=False, comment="ip地址")
    hostname = Column(String(200), comment="主机名")
    mac = Column(String(200), comment="mac地址")
    mac_vender = Column(String(200), comment="主机提供商")
    os_version = Column(String(200), comment="操作系统版本")
    device_type = Column(String(200), comment="设备类型")
    port_nums = Column(INTEGER, comment="主机开发端口数量")
    os_info = Column(String(1000), comment="操作系统信息")
    server_info = Column(String(1000), comment="服务信息")
    job_id = Column(CHAR(32), nullable=False, comment="关联的任务id")
    job_name = Column(String(200), nullable=False, comment="任务名称")
    create_time = Column(DATETIME, comment="结果创建时间")
    insert_time = Column(DATETIME, default=datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'), comment="记录插入时间")


class AMASSET(Base):
    # 表名
    __tablename__ = 'AM_ASSET'
    ID = Column(BIGINT, primary_key=True, nullable=False, comment="id")
    ASSET_CODE = Column(String(50), comment="资产编号")
    ASSET_NAME = Column(String(100), comment="资产名称")
    ASSET_DESC = Column(String(500), comment="资产描述")
    IPV4 = Column(String(20), comment="IPV4")
    IPV6 = Column(String(100), comment="IPV6")
    VIP = Column(String(100), comment="虚拟IP")
    ACC_URL = Column(String(100), comment="访问url")
    ACC_PORT = Column(INTEGER, comment="访问端口")
    PID = Column(BIGINT, default=-1, comment="父id")
    ID_FLAG = Column(String(200), comment="族谱")
    TYPE_ID = Column(BIGINT, comment="资产类型id")
    TYPE2_ID = Column(BIGINT, comment="资产子类型id")
    OS_ID = Column(BIGINT, comment="操作系统id")
    VER = Column(String(10), comment="版本")
    VER0 = Column(String(20), comment="原始版本字串")
    BIZ_ID = Column(BIGINT, comment="业务系统id")
    OWN_ACC = Column(String(50), comment="拥有人帐号")
    RESP_ACC = Column(String(50), comment="责任人帐号")
    VENDOR = Column(String(50), comment="厂商缩写，AM_VENDOR.VENDOR_NAME")
    IS_KEY = Column(SMALLINT, comment="是否关键资产")
    VAL_CIA = Column(SMALLINT, comment="CIA赋值")
    LOCATION = Column(String(200), comment="位置")
    REC_STATE = Column(SMALLINT, comment="记录状态")
    BIZ_STATE = Column(SMALLINT, comment="业务状态")
    AUDIT_ACC = Column(String(50), comment="审核帐号")
    AUDIT_TIME = Column(DATETIME, comment="审核时间")
    CRT_ACC = Column(String(50), nullable=False, comment="创建帐号")
    CRT_TIME = Column(DATETIME, nullable=False, comment="创建时间")
    UPD_ACC = Column(DATETIME, nullable=False, comment="更新账号")
    UPD_TIME = Column(DATETIME, nullable=False, comment="更新时间")
    IS_DEL = Column(SMALLINT, comment="是否删除")
    ORG_ID = Column(BIGINT, comment="所属机构id")
    TENANT_ID = Column(BIGINT)
    TYPE_STR = Column(String(1000))
    ORG_STR = Column(String(1000))
    MAC = Column(String(100), comment="MAC地址")
    ASSET_SOURCE = Column(SMALLINT, comment="资产来源 0 页面新增、导入 1 资产探针 2 流量")
    SOURCE_NAME = Column(String(100), comment="探针设备名称")
    AREA_CODE = Column(String(50), comment="地域编码")
    AREA = Column(String(200), comment="所属地区")
    DOMAIN_ID = Column(BIGINT, comment="安全域id")
    DOMAIN_NAME = Column(String(50), comment="安全域名称")
    DOMAIN2_ID = Column(BIGINT, comment="安全子域id")
    DOMAIN2_NAME = Column(String(50), comment="安全子域名称")
    ENCODE = Column(String(10), comment="字符编码")
    INIT_CMD = Column(String(20), comment="初始指令")
    OWN_PHONE = Column(String(20), comment="使用人电话")

    @staticmethod
    def get_time():
        return datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')


class AMOS(Base):
    # 表名
    __tablename__ = 'AM_OS'
    ID = Column(BIGINT, primary_key=True, nullable=False, comment="id")
    OS_NAME = Column(String(100), comment="资产编号")
    HW_TYPE = Column(String(30), comment="类型字串")
    PID = Column(BIGINT, comment="父id")
    ID_LVL = Column(String(100), comment="层级")
    ID_FLAG = Column(String(200), comment="族谱")
    TYPE_ID = Column(BIGINT, comment="类型ID")
    TYPE_KIND = Column(SMALLINT, comment="1资产分类2操作系统")
    VNODE = Column(SMALLINT, comment="虚拟节点0否1是")
    VENDOR = Column(String(100), comment="厂商")
    IS_DEL = Column(SMALLINT, comment="是否删除")
    OLD_ID = Column(INTEGER)
